﻿using HostedServiceDemo.EfContext;
using HostedServiceDemo.Model;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace BackgroundServiceDemo
{
    public class DBHostedService : BackgroundService
    {
        private readonly ILogger _logger;
        private readonly IServiceScopeFactory _scopeFactory;

        public DBHostedService(ILogger<DBHostedService> logger, IServiceScopeFactory scopeFactory)
        {
            _logger = logger;
            _scopeFactory = scopeFactory;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            // https://stackoverflow.com/questions/48368634/how-should-i-inject-a-dbcontext-instance-into-an-ihostedservice
            // 这里不能直接注入EFContext是因为生命周期问题，BackgroundService是asp.net core开始到结束
            // 而EFContext注入的生命周期是Scoped，在同一个Scope内只初始化一个实例 ，可以理解为（ 每一个request级别只创建一个实例，同一个http request会在一个 scope内）
            // 所以在启动时，会提示我们把EFContext改为单例注入

            using (var scope = _scopeFactory.CreateScope())
            {
                var _context = scope.ServiceProvider.GetRequiredService<EFContext>();
                await _context.Database.EnsureDeletedAsync();
                if (await _context.Database.EnsureCreatedAsync())
                {
                    if (!_context.QuartInfo.Any())
                    {
                        var goodList = new List<QuartzInfo>()
                            {
                                new QuartzInfo(){
                                    guid = Guid.NewGuid().ToString(),
                                    triggerGroup = "TestGroup1",
                                    triggerName = "TestName",
                                    cronExpression = "0 0/1 * * * ? ",
                                    fullClassName = "BackgroundServiceDemo.TestJob",
                                    jobGroup = "jobGroup1",
                                    jobName = "jobName1",
                                },
                            };
                        _context.QuartInfo.AddRange(goodList);
                        await _context.SaveChangesAsync();
                    }
                }
            }
        }
    }
}
